#include <stdio.h>
#include <unistd.h>
#include <sys/select.h>

#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

int main()
{
    //创建侦听套接字
    int listen_sock = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
    if(listen_sock < 0)
    {
        perror("sock");
        return 0;
    }
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(20001);
    addr.sin_addr.s_addr = inet_addr("0.0.0.0");
    //绑定地址信息
    int ret = bind(listen_sock,(struct sockaddr*)&addr,sizeof(addr));
    if(ret < 0)
    {
        perror("bind");
        return 0;
    }
    ret = listen(listen_sock,5);
    if(ret < 0)
    {
        perror("listen");
        return 0;
    }
    //创建一个可读事件，类型为位图
    fd_set readfds;
    //将可读事件中的所有位置为1
    FD_ZERO(&readfds);
    //将可读事件集的0号位置置为1
   // FD_SET(0,&readfds);
    ////监视0号位置(0号位置是标准输入)
    //select(0+1,&readfds,NULL,NULL,NULL);//阻塞
    ////记录输入的内容
    //char buf[1024] = {0};
    ////读0号描述符的内容
    //read(0,buf,sizeof(buf)-1);
    ////打印内容
    //printf("content : %s\n",buf);
    FD_SET(0,&readfds);
    FD_SET(listen_sock,&readfds);
    while(1)
    {
        fd_set tmp = readfds;
        int ret =  select(listen_sock+1,&tmp,NULL,NULL,NULL);//非阻塞
        if(ret < 0)
        {
            perror("select");
            return 0;
        } 
        else if(ret == 0)
        {
            printf("timeout\n");
            continue;
        }
        if(FD_ISSET(0,&tmp))
        {
            //记录输入的内容
            char buf[1024] = {0};
            //读0号描述符的内容
            read(0,buf,sizeof(buf)-1);
            //打印内容
            printf("content : %s\n",buf);
            printf("0 in readfds\n");
        }
        else 
        {
            printf("0 not in readfds\n");
        }
        if(FD_ISSET(listen_sock,&tmp))
        {
            printf("listen_sock in readfds\n");
            accept(listen_sock,NULL,NULL);
        }
        else 
        {
            printf("listen_sock not in readfds\n");
        }

        }
    return 0;
}
